import Vue from 'vue';
import config from './config.js';
import store from '@/store/index.js';
import jwt from '@/utils/jwt.js';
import {RouterMount,createRouter} from 'uni-simple-router';
import { checkToken } from '@/common/http.api.js';

// 初始化
const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,  
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	//权限控制操作
	let loginFlag = jwt.getLogin();
	console.info('路由拦截：' + to.meta.auth + ' 是否登陆：' + loginFlag)
	if (to.meta && to.meta.auth) {
		if(loginFlag){
			//如果token不为空，判断是否有效
			console.info('有token，校验token');
			//校验token是否有效
			checkToken().then(res => {
				if (res.code === 0) {
					next();
				}else{
					jwt.logout();
					next({path:'/pages/common/public/login_one',NAVTYPE: 'push'});
				}
			});
		}else{
			console.info('不存在token，去登陆');
			next({path:'/pages/common/public/login_one',NAVTYPE: 'push'});
		}
	} else {
		console.info('是否登陆：' + loginFlag + ' 名称：' + to.meta.name);
		if (loginFlag && to.meta.name == "login") {
			console.info('去首页。。。')
			next({path:'/pages/tabbar/home/home',NAVTYPE: 'push'});
		} else {
			console.info('next。。。')
			next();
		}
	}
})
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log(to, "全局路由后置守卫");
})
export {
	router,
	RouterMount
}
